import Taro from "@tarojs/taro";

import { getQueryString } from ".";
import { decrypt } from "./aes.js";

const TextDecoder = require('@cto.af/textdecoder')

const logger = Taro.getRealtimeLogManager();

export const requestHis = (url, options) => {
  Taro.showLoading({ title: "加载中...", mask: true });
  const { params, skipError, header, data, backAll = false, ...leftOptions } =
    options || {};
  const queryStr = getQueryString(params);

  const urlWithParams = queryStr ? `${url}?${queryStr}` : url;
  const nwUrl = `${HOST}/api/his${urlWithParams}`;

  const authToken = Taro.getStorageSync("token");
  const tokenHeader = authToken ? { Authorization: `${authToken}` } : {};
  const nwHeader = {
    ...(header || {}),
    ...tokenHeader,
  };

  return new Promise((resolve, reject) => {
    Taro.request({
      ...leftOptions,
      url: nwUrl,
      data: { unitsCode: "072304", ...data },
      method: "POST",
      header: nwHeader,
      success: (res) => {
        Taro.hideLoading();
        
        if (typeof res.data == "string" && res.data.startsWith("ENCRYPT:")) {
          const strs = getDecryptStrAndIv(res.data);
          const jsonstr = decrypt(strs[0], strs[1]);
          res.data = JSON.parse(jsonstr);
          // console.log("-------解密后数据------");
          // console.log(res.data);
        }

        // const {}
        const { data, msg, status } = res.data;

        // data: "";
        // msg: "系统不存在null对应的授权信息，不能校验！";
        // status: "-1";
        if (status === "0") {
          if (backAll) {
            resolve(res.data);
          } else {
            resolve(data);
          }
        } else {
          console.error(res);

          logger.error(nwUrl);
          logger.error(options);
          logger.error(res);

          Taro.showToast({
            title: msg || "网络错误",
            icon: "none",
          });

          reject(msg);
        }
      },

      fail: (err) => {
        Taro.hideLoading();
        console.error(err);

        logger.error("网络错误");
        logger.error(nwUrl);
        logger.error(options);
        logger.error(err);

        const message = err.message || err.errMsg || err;

        Taro.showToast({
          title: message || "网络错误",
          icon: "none",
        });

        reject(message);
      },
    });
  });
};

export default (url, options) => {
  Taro.showLoading({ title: "加载中...", mask: true });
  const { params, skipError, header, ...leftOptions } = options || {};
  const queryStr = getQueryString(params);

  const urlWithParams = queryStr ? `${url}?${queryStr}` : url;
  const nwUrl = `${HOST}/api/ma${urlWithParams}`;

  const authToken = Taro.getStorageSync("token");
  const tokenHeader = authToken ? { Authorization: `${authToken}` } : {};
  const nwHeader = {
    ...(header || {}),
    ...tokenHeader,
  };

  return new Promise((resolve, reject) => {
    Taro.request({
      ...leftOptions,
      url: nwUrl,
      header: nwHeader,
      success: (res) => {
        Taro.hideLoading();
        
        if (typeof res.data == "string" && res.data.startsWith("ENCRYPT:")) {
          const strs = getDecryptStrAndIv(res.data)
          const jsonstr = decrypt(strs[0], strs[1]);
          res.data = JSON.parse(jsonstr);
          // console.log("-------解密后数据------");
          // console.log(res.data);
        }
        
        const { data, msg, code } = res.data;
        console.log(data, "request");
        if (data?.token) {
          Taro.setStorage({ key: "token", data: data?.token || "" });
        }

        if (code === 200) {
          resolve(data);
        } else {
          console.error(res);

          logger.error(nwUrl);
          logger.error(options);
          logger.error(res);

          Taro.showToast({
            title: msg,
            icon: "none",
          });

          reject(msg);
        }
      },

      fail: (err) => {
        Taro.hideLoading();
        console.error(err);

        logger.error("网络错误");
        logger.error(nwUrl);
        logger.error(options);
        logger.error(err);

        const message = err.message || err.errMsg || err;

        Taro.showToast({
          title: message || "网络错误",
          icon: "none",
        });

        reject(message);
      },
    });
  });
};

function getDecryptStrAndIv(str) {
  const [s1, s2] = str.substring(8).split('.')
  const iv = (new TextDecoder('utf-8')).decode(wx.base64ToArrayBuffer(s2)).substring(0, 16)
  return [s1, iv];
}
